package com.example.xgakj.newterminal.ui.framents;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.xgakj.mylibrary.mvp.utils.CommonUtil;
import com.example.xgakj.mylibrary.mvp.utils.ToastUtil;
import com.example.xgakj.newterminal.R;
import com.example.xgakj.newterminal.base.BaseApplication;
import com.example.xgakj.newterminal.base.BaseFragment;
import com.example.xgakj.newterminal.base.Parameters;
import com.example.xgakj.newterminal.beans.CustomerBean;
import com.example.xgakj.newterminal.beans.DeviceBean;
import com.example.xgakj.newterminal.beans.ResultBean;
import com.example.xgakj.newterminal.models.BaseJsonCallBack;
import com.example.xgakj.newterminal.models.QueryModel;
import com.example.xgakj.newterminal.ui.activities.AlarmRecordActivity;
import com.jovision.demo.Play2Activity;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.socks.library.KLog;
import com.tutk.sample.AVAPI.MainActivity2;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 */
public class DeviceDetailFragment extends BaseFragment {

    Unbinder unbinder;
    @BindView(R.id.tv_ID)
    TextView tvID;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_visual)
    TextView tvVisual;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_tel)
    TextView tvTel;
    @BindView(R.id.tv_contact1)
    TextView tvContact1;
    @BindView(R.id.tv_contact2)
    TextView tvContact2;
    @BindView(R.id.tv_taocan)
    TextView tvTaocan;
    @BindView(R.id.tv_community)
    TextView tvCommunity;
    @BindView(R.id.cbx_alarm)
    CheckBox cbxAlarm;
    @BindView(R.id.cbx_defence)
    CheckBox cbxDefence;
    @BindView(R.id.ll_video)
    LinearLayout llVideo;
    private Bundle bundle;
    private CustomerBean customerBean;
    private DeviceBean deviceBean;
    private boolean ignoring;

    public DeviceDetailFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        KLog.d("onCreate");
        bundle = getArguments();
        if (bundle != null) {
            customerBean = (CustomerBean) bundle.getSerializable(Parameters.CUSTOMER_BEAN);
            KLog.d(customerBean.toString());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_device_detail, container, false);
        unbinder = ButterKnife.bind(this, view);
        initViews(customerBean);
        initListners();
        if (getActivity() instanceof AlarmRecordActivity) {
            ((AlarmRecordActivity) getActivity()).setBtnVisible(View.INVISIBLE);
        }

        return view;
    }

    private void initListners() {
        cbxDefence.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                if (!ignoring) {
                    String fname = "cmd_text";
                    String fvalue = "'" + (isChecked ? "1" : "0") + "'";
                    String kvalue = "'" + BaseApplication.usrID + "'";
                    QueryModel.getInstance().update(Parameters.CUSTOMER, "cuid", kvalue, fname, fvalue,
                            new StringCallback() {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    KLog.e(response.body());
                                    String body = response.body();
                                    if (body.contains("OK")) {
                                        ToastUtil.showShort(getActivity(), "修改成功");
                                        setStatus(isChecked ? 0 : 1);
                                    }
                                }
                            });
                }

            }
        });
        cbxAlarm.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
                String param = "732" + BaseApplication.usrID + (isChecked ? "D1" : "D0");
                String[] keys = {"cuid", "ctl"};
                String[] values = {BaseApplication.usrID, param};
                QueryModel.getInstance().sendCommand("fm_ctl", keys, values, new BaseJsonCallBack<ResultBean>(null) {
                    @Override
                    public void onSuccess(Response<ResultBean> response) {
                        ResultBean body = response.body();
                        if (body != null && ("OK").equals(body.getRet())) {
                            ToastUtil.showShort(getActivity(), "修改成功");

                        }
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (getActivity() instanceof AlarmRecordActivity) {
            ((AlarmRecordActivity) getActivity()).setBtnVisible(View.VISIBLE);
        }
        unbinder.unbind();
    }

    private void initViews(CustomerBean table) {
        if (table != null) {
            tvID.setText(table.getCUID());
            setStatus(table.getStatus());
            tvName.setText(table.getName());
            tvAddress.setText(table.getAddress());
            tvTel.setText(table.getPhoneHome());
            tvContact1.setText(table.getMemborMobel1());
            tvContact2.setText(table.getMemborMobel2());
            tvTaocan.setText(table.getTC_Type());
            tvCommunity.setText(table.getPartname());
            queryDeviceDetail(table.getCUID());
        }
    }

    private void queryDeviceDetail(String cuid) {
        String params = "cust_id='00" + cuid + "'";
        String field = "dev_id,dev_bz,recv_date,cust_id,address,port,usr,pwd,ifaddr,srvport";
        QueryModel.getInstance().queryCommon(Parameters.SELECT, Parameters.VIDEODEVICE, field, params,
                new BaseJsonCallBack<List<DeviceBean>>(null) {
                    @Override
                    public void onSuccess(Response<List<DeviceBean>> response) {
                        List<DeviceBean> list = response.body();
                        if (list != null && list.size() > 0) {
                            deviceBean = list.get(0);
                            tvVisual.setText(TextUtils.isEmpty(deviceBean.getAddress()) ? "不可视" : "可视");
                        }
                    }
                });
    }

    /**
     * @param status 设备状态 0布防 1撤防 2不在线
     */
    private void setStatus(int status) {
        ignoring = true;
        switch (status) {
            case 0:
                tvStatus.setText("布防");
                cbxDefence.setEnabled(true);
                cbxDefence.setChecked(true);
                break;
            case 1:
                tvStatus.setText("撤防");
                cbxDefence.setEnabled(true);
                cbxDefence.setChecked(false);
                break;
            case 2:
                tvStatus.setText("不在线");
                cbxDefence.setEnabled(false);
                break;
            default:
        }
        ignoring = false;
    }


    @OnClick(R.id.ll_video)
    public void onViewClicked() {
       checkVideo();
    }
    private void checkVideo() {


        if (deviceBean==null||  CommonUtil.isNull(deviceBean.getAddress())){
            ToastUtil.showShort(getActivity(),"获取不到视频设备地址，无法查看");
            return;
        }
        String address = deviceBean.getAddress();
        int ifaddr=deviceBean.getIfaddr();
        if (ifaddr== Parameters.TUTK){
            Intent intent=new Intent(getActivity(), MainActivity2.class);
            intent.putExtra(Parameters.VIDEO_UID,address);
            intent.putExtra(Parameters.VIDEO_PASSWORD,deviceBean.getPwd());
            startActivity(intent);
        }else if (ifaddr==Parameters.YUN_SHI_TONG){
            Intent intent=new Intent(getActivity(), Play2Activity.class);
            intent.putExtra(Parameters.DEVICE,deviceBean);
            startActivity(intent);
            KLog.d("进入云视通");
        }else {
            ToastUtil.showShort(getActivity(),"该设备不支持视频播放");
        }
    }
}
